import Character from "./Character";
const {ccclass, property} = cc._decorator;
@ccclass
export default class Npc extends Character{
    /** Npc数据 */
    private _npc:QM.Npc;
    set npc(value){
        this._npc = value;
        this.dir = value.dir;
        this.action = value.action;
        this.node.name = value.name; 
        this.init();
    }
    get npc(){
        return this._npc;
    }

    /** 巡场路径 */
    path:cc.Vec2[];
    /** 是否正在巡场 */
    private isTour:boolean=false
    /** 最后一次改变的位置 */
    private lastP:cc.Vec2;

    /** 动画组件 */
    private animCom:cc.Animation;


    /** 当前Npc所拥有的动作名称 */
    private animNameRow:string[]=[];


    onLoad(){
        this.node.active = false;
        this.animCom = this.getComponent(cc.Animation);
        this.node.on(cc.Node.EventType.TOUCH_END,this.touchEnd,this);
    }

    update(){              
        
        if(this.path && !this.isTour && QM.game.state==QM.gameState.normal){
            this.TourMove();
        }
    }


    /** 初始化Npc */
    init(){      
        this.node.active = true; 
        //加载npc的图片资源
        cc.loader.loadRes("Npc/"+this.npc.texture,cc.SpriteAtlas,(err,atlas:cc.SpriteAtlas)=>{
            //101-108为八方向图        
            for(var i=1;i<=8;i++){
                //添加八方向待机动画
                var sp = atlas.getSpriteFrame("10"+i);
                if(sp){
                    var clip = cc.AnimationClip.createWithSpriteFrames([sp],1);
                    clip.name = "1_"+i;
                    clip.wrapMode = cc.WrapMode.Normal;
                    this.animCom.addClip(clip)    
                    this.animNameRow.push(clip.name);
                }
                //添加八方向行走图 如果当前方向存在图片，则每个方向有4张图片
                var sp1 = atlas.getSpriteFrame("2"+i+"1");
                if(sp1){
                    var sp2 = atlas.getSpriteFrame("2"+i+"2");
                    var sp3 = atlas.getSpriteFrame("2"+i+"3");
                    var sp4 = atlas.getSpriteFrame("2"+i+"4");
                    var sps = [sp1,sp2,sp3,sp4];
                    var clip = cc.AnimationClip.createWithSpriteFrames( sps as [cc.SpriteFrame],4);
                    clip.name = "2_"+i;
                    clip.wrapMode = cc.WrapMode.Loop;
                    this.animCom.addClip(clip);
                    this.animNameRow.push(clip.name);
                }
                //添加默认动作1 如果当前方向存在图片，则每个方向有2张图片
                var asp1 = atlas.getSpriteFrame("3"+i+"1");
                if(asp1){
                    var asp2 = atlas.getSpriteFrame("3"+i+"2");
                    var sps = [asp1,asp2];
                    var clip = cc.AnimationClip.createWithSpriteFrames( sps as [cc.SpriteFrame],2);
                    clip.name = "3_"+i;
                    clip.wrapMode = cc.WrapMode.Loop;
                    this.animCom.addClip(clip);
                    this.animNameRow.push(clip.name);
                }              
            }

            //补几个动画
            this.animNameRow.push("2_6","2_8","3_6","3_8")

            //创建完动画后,显示             
            this.playAnim()          
        })       
        this.zIndex();
    }

    /**
     * 播放动画
     */
    playAnim(){
        var action = this.action;
        var dir = this.dir;
        var sX=1;
        if(action!=1){         
            switch(dir){
                case 8:
                    dir = 5;
                    sX = -1;
                break;
                case 6:
                    dir = 7;
                    sX = -1;                
                break;
                case 1: 
                    dir = 5;
                    if(! (this.lastDir%2) ){
                        sX=-1
                    }
                break;
                case 2:
                    dir = 7;
                    if(! (this.lastDir%2) ){
                        sX=-1
                    }                    
                break;
                case 3:
                    if(this.lastDir==5||this.lastDir==1){
                        dir = 5
                    }else{
                        dir = 7
                    }
                break;
                case 4:
                    sX = -1;
                    if(this.lastDir==1||this.lastDir==8){
                        dir = 5
                    }else{
                        dir = 7
                    }
                break;
            }
        }

        
        var name = action+"_"+dir;

        if(this.animNameRow.indexOf(name)>-1){
            this.node.scaleX = sX;
            this.animCom.play(name);
        }

    }

    /** Npc被点击时 */
    touchEnd(){
        //当npc点击时,先判断needIf是否存在
        var needIf = this.npc.needIf;
        if(needIf){
            //判断是否满足条件
            var flag = true;
            if(needIf.if.itemId){
                //如果存在物品条件,查找背包是否有某物品
                if(!QM.game.isPackItem(needIf.if.itemId)){
                    flag = false;
                }                
            }
            if(needIf.if.taskId){
                if(!QM.game.isTask(needIf.if.taskId)){
                    flag = false
                }
            }
            if(flag){
                this.npc.plot = needIf.plot;
                delete this.npc.needIf;
            }
        }
        var plots = this.npc.plot;              
        if(plots){
            var event = new cc.Event.EventCustom("NpcPlot",true);
            event.setUserData([...plots]);
            this.node.dispatchEvent(event);
        }
        if(this.isTour){
            this.node.stopAllActions()
            this.action = 1;
            this.isTour = false;
        }        
    }

    /** 巡场 */
    TourMove(){
        
        

        this.isTour = true;
        
        var paths = this.path.shuffle().slice(0, Math.floor(this.path.length/2));
        
      
        


        var pStart = this.node.position;
        this.action = 2;
        var tempActionRow = [];
        paths.forEach(pTarget=>{
            var angle = cc.v2(1,0).signAngle(pTarget.sub(pStart))*180/Math.PI;
            var dir = QM.getDirForAngle(angle);
            var a1 = cc.callFunc(()=>{
                this.dir = dir;
            })
            var a2 = cc.moveTo( pTarget.sub(pStart).mag()/60,pTarget );
            tempActionRow.push(a1,a2);
            pStart = pTarget;
        })
        var a3 = cc.delayTime(1);
        var an = cc.callFunc(()=>{
            this.isTour = false;
        })
        tempActionRow.push(a3,an);
        this.node.runAction( cc.sequence(tempActionRow) );
    }

}
